﻿using AutoMapper;
using B.S.Filtration.Domain;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Write.Api.Application.Command.FiltrateCommand;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Write.Api.Application.CommandHander.FiltrateCommandHander
{
    public class CreateFiltrateCommandHander : IRequestHandler<CreateFiltrateCommand, APIResult<int>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public CreateFiltrateCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<APIResult<int>> Handle(CreateFiltrateCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var model = mapper.Map<Filtrate>(request);

            model.Del = false;

            result.data = await db.Insertable(model).ExecuteCommandAsync();

            if (result.data > 0)
            {
                result.code = APIResultCode.success;
                result.msg = "添加过滤液成功";
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "添加过滤液失败";
            }

            return result;
        }
    }
}
